package com.dashu.base.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

public class SystemUtils {

    /**
     * 判断运行系统是linux 还是windows
     *
     * @return
     */
    public static boolean isOSWindows() {
        //获取系统配置文件
        Properties properties = System.getProperties();

        String os = properties.getProperty("os.name");

        return os.toUpperCase().contains("WINDOWS");
    }


    /**
     * 获取本地IP地址
     */
    public static List<String> getLocalIP() {
        if (isOSWindows()) {
            List<String> ips = new ArrayList<>();
            try {
                ips.add(InetAddress.getLocalHost().getHostAddress());
                return ips;
            } catch (UnknownHostException e) {
                ips.add("127.0.0.1");
                return ips;
            }
        } else {
            return getLinuxLocalIp();
        }
    }


    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     */
    private static List<String> getLinuxLocalIp() {
        List<String> ip = new ArrayList<>();
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                ip.add(ipaddress);
                                System.out.println(ipaddress);
                                break;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            System.out.println("获取ip地址异常");
            String ipStr = "127.0.0.1";
            ip.add(ipStr);
        }
        System.out.println("IP:" + ip);
        return ip;
    }

}
